﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace h5上传文件带进度条.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Upload()
        {
            #region 上传文件
            string msg = string.Empty;
            var flist = Request.Files;
            int flag = 0;//是否保存成功
            try
            {
                for (int i = 0; i < flist.Count; i++)
                {
                    string FilePath = Request.PhysicalApplicationPath + "_files";//获取保存目录，绝对路径                    
                    DateTime now = DateTime.Now;
                    var c = flist[i];
                    BinaryReader r = new BinaryReader(c.InputStream);

                    if (c.ContentLength < 10 * 1024 * 1024)//判断大小
                    {
                        if (!Directory.Exists(FilePath))
                        {
                            Directory.CreateDirectory(FilePath);//路径不存在则创建
                        }
                        string newFileName = now.ToString("yyyyMMddHHmmssffff");
                        string[] arr = null;
                        if (c.ContentType.IndexOf("/") >= 0)
                        {
                            arr = c.ContentType.Split('/');
                        }
                        if (arr != null)
                        {
                            newFileName = newFileName + "." + arr[1];
                        }
                        else
                        {
                            newFileName = newFileName + c.FileName;
                        }
                        FilePath = Path.Combine(FilePath, newFileName);
                        c.SaveAs(FilePath);
                        flag = 1;
                        msg = "保存成功";
                    }
                    else
                    {
                        flag = 0;
                        msg = "文件太大，请选择小于10M的。";
                    }
                    r.Close();
                    c.InputStream.Close();
                }
            }
            catch (Exception ex)
            {
                flag = 0;
                msg = "上传图片" + ex.Message;
            }
            #endregion
            return Json(new { flag = flag, msg = msg });
        }
    }
}